package service

import (
	"cr.org/model"
	"cr.org/modules/repository"
	"cr.org/utils"
)

type otherService struct {
}

func (s otherService) SaveAiModels(arg model.AiModelsT) (err error) {
	arg.Id = utils.GetSoftId()
	err = repository.OtherRepository.SaveAiModels(&arg)
	return
}

func (s otherService) GetAiModelDetail(id int64) (m model.AiModelsT, err error) {
	m, err = repository.OtherRepository.FindAiModelsById(id)
	return
}

func (s otherService) SaveAiDraw(arg model.AiDrawT, uid int64) (err error) {
	arg.Id = utils.GetSoftId()
	arg.UserId = uid
	err = repository.OtherRepository.SaveAiDraw(&arg)
	return
}

func (s otherService) UpdateThumbsUpAddOne(uid, drawId int64) (err error) {
	mt, err := repository.OtherRepository.CheckThumbsUp(uid, drawId)
	if err != nil {
		return err
	}
	m, err := repository.OtherRepository.FindAiDrawById(drawId)
	if err != nil {
		return err
	}
	if mt.UserId == 0 && mt.DrawId == 0 {
		m.ThumbsUp++
		mt.UserId = uid
		mt.DrawId = drawId
		if err := repository.OtherRepository.InsertThumbsUpMap(mt); err != nil {
			return err
		}
	} else {
		m.ThumbsUp--
		if err := repository.OtherRepository.DeleteThumbsUpMap(mt); err != nil {
			return err
		}
	}
	if m.ThumbsUp < 0 {
		m.ThumbsUp = 0
	}
	err = repository.OtherRepository.SaveAiDraw(&m)
	return
}

func (s otherService) CheckThumbsUpStatus(uid, drawId int64) (b bool, err error) {
	mt, err := repository.OtherRepository.CheckThumbsUp(uid, drawId)
	if err != nil {
		return
	}
	b = mt.UserId != 0 && mt.DrawId != 0
	return
}

func (s otherService) GetAiDrawTop5(arg model.SearchAiDraw, uid int64) (li []model.AiDrawT, err error) {
	if arg.Page < 1 {
		arg.Page = 1
	}
	if arg.PageSize < 5 {
		arg.PageSize = 5
	}
	if arg.OrderBy == "" {
		arg.OrderBy = "thumbs_up"
	}
	if arg.Sort == "" {
		arg.Sort = "desc"
	}
	li, err = repository.OtherRepository.FindAiDraw(arg, uid)
	return
}

func (s otherService) AiDrawPage(arg model.SearchAiDraw, uid int64) (li []model.AiDrawT, total int64, err error) {
	if arg.Page < 1 {
		arg.Page = 1
	}
	if arg.PageSize < 5 {
		arg.PageSize = 5
	}
	if arg.OrderBy == "" {
		arg.OrderBy = "thumbs_up"
	}
	if arg.Sort == "" {
		arg.Sort = "desc"
	}
	li, total, err = repository.OtherRepository.FindAiDrawPage(arg, uid)
	return
}

func (s otherService) AiModelsPage(arg model.SearchAiModels) (li []model.AiModelsT, total int64, err error) {
	li, total, err = repository.OtherRepository.FindAiModelsPage(arg)
	return
}
